<template>
  <van-list
    :error.sync="error"
    :finished="finished"
    @load="onLoad"
    error-text="请求失败，点击重新加载"
    finished-text="没有更多了"
    v-model="loading"
  >
    <comment-item :comment="item" :key="index" v-for="item,index in list"></comment-item>
  </van-list>
</template>

<script>
import { getComment } from '@/api/comment'
import CommentItem from './comment-item.vue'

export default {
  name: 'CommentList',
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  components: {
    CommentItem
  },
  data () {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null,
      limit: 10,
      error: false
    }
  },
  created () {
    this.onLoad()
  },
  methods: {
    async onLoad () {
      try {
        const { data } = await getComment({
          type: 'a',
          source: Number(this.source),
          offset: this.offset,
          limit: this.limit
        })
        // console.log(data)
        const { results } = data.data
        // console.log(typeof results)
        this.list.push(...results)
        this.loading = false

        this.$emit('onload-success', data.data)
        // if (Math.random() > 0.5) {
        //   JSON.parse('kdsjhfk')
        // }

        if (results.length) {
          this.offset = data.data.last_id
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }

    }
  }
}
</script>
<style lang="less" scoped>
</style>